package com.crm.api.controller;

import com.crm.api.common.JwtUtil;
import com.crm.api.common.Result;
import com.crm.api.common.ResultCode;
import com.crm.api.controller.dto.EmployeeProfileDTO;
import com.crm.api.controller.dto.LoginDTO;
import com.crm.api.controller.dto.PasswordDTO;
import com.crm.api.entity.Employee;
import com.crm.api.mapper.EmployeeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@Slf4j
@RestController
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 登录
     */
    @PostMapping("/auth/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginDTO loginDTO) {
        log.info("用户登录: {}", loginDTO.getUsername());

        // 认证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword()));

        // 设置认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 生成JWT
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = jwtUtil.generateToken(userDetails);

        // 查询员工信息
        Employee employee = employeeMapper.findByUsername(loginDTO.getUsername());

        // 更新最后登录时间
        employeeMapper.updateLastLoginTime(employee.getId(), new Date());

        // 构建用户信息
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", employee.getId());
        userInfo.put("employeeCode", employee.getEmployeeCode());
        userInfo.put("username", employee.getUsername());
        userInfo.put("realName", employee.getRealName());
        userInfo.put("gender", employee.getGender());
        userInfo.put("phone", employee.getPhone());
        userInfo.put("email", employee.getEmail());
        userInfo.put("department", employee.getDepartment());
        userInfo.put("position", employee.getPosition());
        userInfo.put("role", employee.getRole());
        userInfo.put("hireDate", employee.getHireDate());
        userInfo.put("isActive", employee.getIsActive());

        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userInfo", userInfo);
        result.put("permissions", new String[]{"*"}); // 简化权限处理

        return Result.success(result);
    }

    /**
     * 登出
     */
    @PostMapping("/auth/logout")
    public Result<Void> logout() {
        // 清除Spring Security上下文
        SecurityContextHolder.clearContext();
        return Result.success();
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/auth/current")
    public Result<Map<String, Object>> getCurrentUser() {
        // 获取当前认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        // 查询员工信息
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return Result.error(ResultCode.UNAUTHORIZED);
        }

        // 构建用户信息
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", employee.getId());
        userInfo.put("employeeCode", employee.getEmployeeCode());
        userInfo.put("username", employee.getUsername());
        userInfo.put("realName", employee.getRealName());
        userInfo.put("gender", employee.getGender());
        userInfo.put("phone", employee.getPhone());
        userInfo.put("email", employee.getEmail());
        userInfo.put("department", employee.getDepartment());
        userInfo.put("position", employee.getPosition());
        userInfo.put("role", employee.getRole());
        userInfo.put("hireDate", employee.getHireDate());
        userInfo.put("isActive", employee.getIsActive());

        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("userInfo", userInfo);
        result.put("permissions", new String[]{"*"}); // 简化权限处理

        return Result.success(result);
    }

    /**
     * 修改密码
     */
    @PostMapping("/auth/change-password")
    public Result<Void> changePassword(@Valid @RequestBody PasswordDTO passwordDTO) {
        // 获取当前认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        // 查询员工信息
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return Result.error(ResultCode.UNAUTHORIZED);
        }

        // 验证旧密码
        if (!passwordEncoder.matches(passwordDTO.getOldPassword(), employee.getPassword())) {
            return Result.error(ResultCode.VALIDATE_FAILED.getCode(), "旧密码不正确");
        }

        // 更新密码
        String encodedPassword = passwordEncoder.encode(passwordDTO.getNewPassword());
        employeeMapper.updatePassword(employee.getId(), encodedPassword);

        log.info("用户 {} 修改了密码", username);
        return Result.success();
    }

    /**
     * 更新用户个人资料
     */
    @PutMapping("/api/auth/profile")
    public Result<Employee> updateUserProfile(@Valid @RequestBody EmployeeProfileDTO profileDTO) {
        // 获取当前认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        // 查询员工信息
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return Result.error(ResultCode.UNAUTHORIZED);
        }

        // 更新个人资料
        employeeMapper.updateProfile(
                employee.getId(),
                profileDTO.getRealName(),
                profileDTO.getGender(),
                profileDTO.getPhone(),
                profileDTO.getEmail());

        // 获取更新后的用户信息
        Employee updatedEmployee = employeeMapper.findById(employee.getId());
        updatedEmployee.setPassword(null); // 出于安全考虑，不返回密码

        log.info("用户 {} 更新了个人资料", username);
        return Result.success(updatedEmployee);
    }

    /**
     * 更新用户密码
     */
    @PutMapping("/api/auth/password")
    public Result<Void> updateUserPassword(@Valid @RequestBody PasswordDTO passwordDTO) {
        // 获取当前认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        // 查询员工信息
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return Result.error(ResultCode.UNAUTHORIZED);
        }

        // 验证旧密码
        if (!passwordEncoder.matches(passwordDTO.getOldPassword(), employee.getPassword())) {
            return Result.error(ResultCode.VALIDATE_FAILED.getCode(), "旧密码不正确");
        }

        // 更新密码
        String encodedPassword = passwordEncoder.encode(passwordDTO.getNewPassword());
        employeeMapper.updatePassword(employee.getId(), encodedPassword);

        log.info("用户 {} 更新了密码", username);
        return Result.success();
    }
}